<template>
  <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false" title="客户端管理">
        <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
          <template #statusSlot="{ model, field }">
            <n-input v-model:value="model[field]" />
          </template>
        </BasicForm>
      </n-card>
    </div>
    <n-card :bordered="false" class="mt-4 proCard">
      <BasicTable :columns="columns" :request="loadDataTable" :row-key="(row) => row.id" ref="actionRef"
        :actionColumn="actionColumn" @update:checked-row-keys="onCheckedRow" :bordered="false">
        <template #tableTitle>
          <n-button type="primary" :on-click="handleEdit.bind(null, {}, true)">
            <template #icon>
              <n-icon>
                <PlusOutlined />
              </n-icon>
            </template>
            添加客户端
          </n-button>
        </template>
        <template #action>
          <TableAction />
        </template>
      </BasicTable>
    </n-card>

    <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" :title="editTitle"
      style="width: 720px;border-radius: 8px;">
      <n-form :model="fromValues" :rules="rules" ref="formRef" label-placement="top" :label-width="120" class="py-4">
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="12" label="客户端名称" path="clientName">
            <n-input maxlength="120" show-count placeholder="请输入客户端名称" v-model:value="fromValues.clientName" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="客户端密钥过期时间 为空永不过期" path="clientSecretExpiresAt">
              <n-date-picker v-model:formatted-value="fromValues.clientSecretExpiresAt" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" clearable 
              placeholder="请输入客户端密钥过期时间 为空永不过期" style= "width:100%"/>
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="重定向URI" path="redirectUris">
            <n-input maxlength="256" show-count placeholder="请输入重定向URI" v-model:value="fromValues.redirectUris" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="客户端认证方法" path="clientAuthenticationMethods">
            <n-input maxlength="256" show-count placeholder="请输入客户端认证方法" v-model:value="fromValues.clientAuthenticationMethods" />
          </n-form-item-gi>
          <n-form-item-gi :span="24" label="权限范围" path="scopeList">
            <n-select multiple v-model:value="fromValues.scopeList" placeholder="请选择权限范围"
              :options="scopeOptions" />
          </n-form-item-gi>
          <n-form-item-gi :span="24" label="认证类型" path="authorizedGrantTypesList">
            <n-select multiple v-model:value="fromValues.authorizedGrantTypesList" placeholder="请选择认证类型"
              :options="grantTypes" />
          </n-form-item-gi>
          <n-form-item-gi :span="24" label="客户端设置" path="clientSettings">
            <n-input maxlength="300" show-count type="textarea" :autosize="{
              minRows: 3,
              maxRows: 5
            }" v-model:value="fromValues.clientSettings" filterable placeholder="请输入客户端设置" />
          </n-form-item-gi>
          <n-form-item-gi :span="24" label="令牌设置" path="tokenSettings">
            <n-input maxlength="600" show-count type="textarea" :autosize="{
              minRows: 3,
              maxRows: 5
            }" v-model:value="fromValues.tokenSettings" filterable placeholder="请输入令牌设置" />
          </n-form-item-gi>
          <n-form-item-gi :span="24" label="客户端说明" path="clientDesc">
            <n-input maxlength="300" show-count type="textarea" :autosize="{
              minRows: 3,
              maxRows: 5
            }" v-model:value="fromValues.clientDesc" filterable placeholder="请输入客户端说明" />
          </n-form-item-gi>
        </n-grid>
      </n-form>
      <div style="justify-content: end;display: flex;">
        <n-space>
          <n-button ghost icon-placement="left" @click="handleCloseModel">
            取消
          </n-button>
          <n-button type="primary" :loading="formBtnLoading" @click="confirmForm">提交</n-button>
        </n-space>
      </div>
    </n-modal>

    <n-modal v-model:show="showSecretModal" :mask-closable="false" preset="dialog" title="查看客户端秘钥" positive-text="确认"
      negative-text="取消" @positive-click="claseSecretModal" @negative-click="claseSecretModal">
      <span>{{ clientSecret }}</span>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, h, onMounted } from 'vue';
import { useMessage, useDialog, type FormRules } from 'naive-ui';
import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
import { BasicTable, TableAction } from '@/components/Table';
import { clientsPages, saveClient, updateClient, removeClient, viewSecret, resetSecret,viewClientKey } from '@/api/system/client';
import { dictGroup } from '@/api/system/dict';
import { columns } from './columns';
import { PlusOutlined, DeleteOutlined, EditOutlined, EyeOutlined, FileDoneOutlined } from '@vicons/antd';
import { ResultEnum } from '@/enums/httpEnum';
const message = useMessage();
const actionRef = ref();
const isAdd = ref(true);
const showModal = ref(false);
const formBtnLoading = ref(false);
const editTitle = ref('');
const dialog = useDialog();
const formRef: any = ref(null);
const showSecretModal = ref(false);
const clientSecret = ref('');
const grantTypes = ref([]);
const scopeOptions = ref([]);
let fromValues = reactive({
  id: null,
  clientName: '',
  scopeList: null,
  authorizedGrantTypesList: null,
  redirectUris: null,
  clientSecretExpiresAt: null,
  clientDesc: '',
  clientSettings:'',
  tokenSettings:'',
  clientAuthenticationMethods:''
});
/**
 * 表格查询参数定义
 */
const schemas: FormSchema[] = [
  {
    field: 'clientName',
    component: 'NInput',
    label: '客户端名称',
    componentProps: {
      placeholder: '请输入客户端名称',
    },
  },
  {
    field: 'clientId',
    component: 'NInput',
    label: '客户端ID',
    componentProps: {
      placeholder: '请选择客户端ID',
    },
  },
];
const rules: FormRules = {
  clientName: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入客户端名称',
  },
  scopeList: {
    type: 'array',
    required: true,
    trigger: ['blur', 'change'],
    message: '请选择权限范围',
  },
  authorizedGrantTypesList: {
    type: 'array',
    required: true,
    trigger: ['blur', 'change'],
    message: '请选择认证类型',
  },
  redirectUris: [
    {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入重定向url',
    },
    { pattern: /^[^\u4e00-\u9fa5]+$/, trigger: ['blur', 'input'], message: '不能输入中文' },
  ],
  clientSettings: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入客户端设置',
  },
  tokenSettings: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入令牌设置',
  },
  clientAuthenticationMethods:{
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入客户端认证方法',
  }
};
/**
 * 创建操作栏工具
 * @param record 
 */
function createActions(record) {
  return [
    {
      label: '删除',
      type: 'error',
      // 配置 color 会覆盖 type
      color: 'red',
      icon: DeleteOutlined,
      onClick: handleDelete.bind(null, record),
      // 根据业务控制是否显示 isShow 和 auth 是并且关系
      ifShow: () => {
        return true;
      },
      // 根据权限控制是否显示: 有权限，会显示，支持多个
      //auth: ['basic_list'],
    },
    {
      label: '编辑',
      type: 'primary',
      icon: EditOutlined,
      onClick: handleEdit.bind(null, record, false),
      ifShow: () => {
        return true;
      },
      //auth: ['basic_list'],
    },
    {
      label: '查看秘钥',
      type: 'success',
      icon: EyeOutlined,
      onClick: openSecretModal.bind(null, record),
      ifShow: () => {
        return true;
      },
      //auth: ['basic_list'],
    },
    {
      label: '查看加密KEY',
      type: 'success',
      icon: EyeOutlined,
      onClick: openClientKey.bind(null, record),
      ifShow: () => {
        return true;
      },
      //auth: ['basic_list'],
    },
    {
      label: '重置秘钥',
      type: 'warning',
      icon: FileDoneOutlined,
      onClick: handleResetSecret.bind(null, record),
      ifShow: () => {
        return true;
      },
      //auth: ['basic_list'],
    },
  ];
}
/**
 * 表格查询注册
 */
const [register, { getFieldsValue }] = useForm({
  gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
  labelWidth: 120,
  schemas,
});
/**
 * 定义操作栏
 */
const actionColumn = reactive({
  width: 350,
  title: '操作',
  key: 'action',
  fixed: 'cen',
  render(record) {
    return h(TableAction as any, {
      style: 'text',
      actions: createActions(record),
    });
  },
});
/**
 * 获取分页数据
 * @param res 
 */
const loadDataTable = async (res: any) => {
  return await clientsPages({ ...getFieldsValue(), ...res });
};
/**
 * 查询
 */
function handleSubmit() {
  reloadTable();
}
/**
 * 重置查询
 */
function handleReset() {
  reloadTable();
}
/**
 * 选中的行
 * @param rowKeys 
 */
function onCheckedRow(rowKeys: any[]) {
  console.log(rowKeys);
}
/**
 * 刷新表格
 */
function reloadTable() {
  actionRef.value.reload();
}
function resetFrom() {
  fromValues = Object.assign(fromValues, {
    id: null,
    clientName: '',
    scopeList: null,
    authorizedGrantTypesList: null,
    redirectUris: null,
    clientSecretExpiresAt: null,
    clientDesc: '',
    clientSettings:'',
    tokenSettings:'',
    clientAuthenticationMethods:''
  });
}
/**
 * 新增编辑提交数据
 * @param e 
 */
function confirmForm(e: any) {
  e.preventDefault();
  formRef.value.validate(async (errors) => {
    if (!errors) {
      formBtnLoading.value = true;
      let data: any;
      if (isAdd.value) {
        data = await saveClient(fromValues);
      } else {
        data = await updateClient(fromValues);
      }
      if (data.code !== ResultEnum.SUCCESS) {
        const resultMsg = (data.data !== null || data.data !== '') ? data.data : '';
        message.error(data.msg + '-' + resultMsg);
        formBtnLoading.value = false;
      }
      if (data.code === ResultEnum.SUCCESS) {
        message.success(data.msg);
        showModal.value = false;
        resetFrom();
        reloadTable();
      }
      formBtnLoading.value = false;
    } else {
      message.error('请填写完整信息');
    }
    formBtnLoading.value = false;
  });
}
/**
 * 新增编辑打开model
 * @param record 
 * @param addStatus 
 */
function handleEdit(record: Recordable, addStatus: boolean) {
  showModal.value = true;
  isAdd.value = addStatus;
  if (addStatus) {
    editTitle.value = `新增客户端`;
  } else {
    editTitle.value = `编辑 ${record.clientName}`;
    fromValues = Object.assign(fromValues, record);
  }
}
/**
 * 新增编辑关闭model
 */
function handleCloseModel() {
  resetFrom();
  showModal.value = false;
}
/**
 * 删除确认
 * @param record 
 */
function handleDelete(record: Recordable) {
  dialog.warning({
    title: '警告',
    content: `确定删除${record.clientName}吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const data = await removeClient({ id: record.id });
      if (data.code !== ResultEnum.SUCCESS) {
        const resultMsg = (data.data !== null || data.data !== '') ? data.data : '';
        message.error(data.msg + '-' + resultMsg);
      }
      if (data.code === ResultEnum.SUCCESS) {
        message.success(data.msg);
        showModal.value = false;
        reloadTable();
      }
    },
  })
}
/**
 * 查看客户端秘钥打开弹框
 */
function openSecretModal(record: Recordable) {
  message.loading('秘钥获取中...', {
    duration: 300,
    onAfterLeave: async () => {
      const secret = await viewSecret({ id: record.id });
      if (secret.code !== ResultEnum.SUCCESS) {
        const resultMsg = secret.data ? secret.data : '';
        message.error(secret.msg + '-' + resultMsg);
      }
      if (secret.code === ResultEnum.SUCCESS) {
        clientSecret.value = secret.data;
        showSecretModal.value = true;
      }
    }
  })
}

/**
 * 查看客户端加密KEY打开弹框
 */
function openClientKey(record: Recordable) {
  message.loading('加密KEY获取中...', {
    duration: 300,
    onAfterLeave: async () => {
      const secret = await viewClientKey({ id: record.id });
      if (secret.code !== ResultEnum.SUCCESS) {
        const resultMsg = secret.data ? secret.data : '';
        message.error(secret.msg + '-' + resultMsg);
      }
      if (secret.code === ResultEnum.SUCCESS) {
        dialog.info({
          title: '客户端加密KEY',
          content: `${secret.data}`,
          positiveText: '确定',
          negativeText: '取消',
        })
      }
    }
  })
}

/**
 * 查看客户端秘钥关闭弹框
 */
function claseSecretModal() {
  showSecretModal.value = false;
}
/**
 * 重置秘钥
 * @param record 
 */
async function handleResetSecret(record: Recordable) {
  dialog.warning({
    title: '警告',
    content: `确定重置${record.clientName}的秘钥吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const data = await resetSecret({ id: record.id });
      if (data.code !== ResultEnum.SUCCESS) {
        const resultMsg = (data.data !== null || data.data !== '') ? data.data : '';
        message.error(data.msg + '-' + resultMsg);
      }
      if (data.code === ResultEnum.SUCCESS) {
        message.success(data.msg);
        showModal.value = false;
        reloadTable();
      }
    },
  })
}
/**
 * 认证类型
 */
async function getGrantTypes() {
  const data = await dictGroup({ dictGroup: 'grant_type' });
  const arry = data.map(item => ({ label: item.dictName, value: item.dictValue }));
  grantTypes.value = arry;
}
/**
 * 访问权限
 */
async function getScopes() {
  const data = await dictGroup({ dictGroup: 'oauth_scope' });
  const arry = data.map(item => ({ label: item.dictName, value: item.dictValue }));
  scopeOptions.value = arry;
}
onMounted(() => {
  getGrantTypes();
  getScopes();
});

</script>

<style lang="less" scoped></style>
